package com.huwaiwai.nio.demo01;

import com.huwaiwai.nio.utils.ChannelUtils;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by huweiwei on 2017/4/20.
 */
public class MyFileChannel {

    public static void main(String [] args) throws IOException {

//        test01();
        test02();

    }

    public static void test01() throws IOException {
        RandomAccessFile accessFile = new RandomAccessFile("C:\\test\\src\\main\\java\\com\\huwaiwai\\nio\\file\\nio-data.txt", "rw");
        FileChannel fileChannel = accessFile.getChannel();
        //创建缓冲区
        ByteBuffer buf = ByteBuffer.allocate(48);
        int bytesRead = fileChannel.read(buf);
        while (bytesRead != -1) {
            System.out.println("读取" + bytesRead);
            System.out.println(ChannelUtils.read(buf));
            buf.clear();
            bytesRead = fileChannel.read(buf);
        }
        accessFile.close();
    }

    public static void test02() throws IOException {
        RandomAccessFile accessFile = new RandomAccessFile("C:\\test\\src\\main\\java\\com\\huwaiwai\\nio\\file\\nio-data.txt", "rw");
        FileChannel fileChannel = accessFile.getChannel();
        //创建缓冲区
        ByteBuffer buf = ByteBuffer.allocate(48);
        int bytesRead = fileChannel.read(buf);
        while (bytesRead != -1) {
            System.out.println("读取" + bytesRead);
            System.out.println(ChannelUtils.read(buf));
            buf.compact();
            bytesRead = fileChannel.read(buf);
        }
        accessFile.close();
    }


}
